package com.witframework.webroot.framework.webresource.components.jmesa;



import static org.jmesa.facade.TableFacadeFactory.createTableFacade;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.facade.TableFacade;
import org.jmesa.view.editor.DateCellEditor;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlRow;
import org.jmesa.view.html.component.HtmlTable;
import org.jmesa.worksheet.Worksheet;
import org.jmesa.worksheet.WorksheetCallbackHandler;
import org.jmesa.worksheet.WorksheetColumn;
import org.jmesa.worksheet.WorksheetRow;
import org.jmesa.worksheet.WorksheetUtils;
import org.jmesa.worksheet.editor.CheckboxWorksheetEditor;

import com.witframework.baseapp.security.BaseUser;
import com.witframework.baseapp.security.BaseUser;
import com.witframework.core.WitFrameWork;
import com.witframework.core.logic.IBaseService;
import com.witframework.web.mvc.WebContext;

/**
 * Create an editable worksheet.
 * 
 * @since 2.3
 * @author Jeff Johnston
 */
public class WorksheetPresidentController{
    private IBaseService getUserService() {
		return WitFrameWork.getSimpleBaseService(BaseUser.class);
	}
    public String executor(WebContext webContext) {
		List<BaseUser> items = getUserService().findBy(webContext.getFilter());
        TableFacade tableFacade = createTableFacade("user", webContext.getHttpRequest());
        tableFacade.setEditable(true); // switch to flip that turns the table editable        
        saveWorksheet(tableFacade);        
        tableFacade.setItems(items); // set the items
        String html = getHtml(tableFacade);
        webContext.setAttribute("presidents", html); // Set the Html in the request for the JSP.
		
		return "controller:/basic.jsp";
    }

    /**
     * An example of how to save the worksheet.
     */
    private void saveWorksheet(TableFacade tableFacade) {
        Worksheet worksheet = tableFacade.getWorksheet();
        if (!worksheet.isSaving() || !worksheet.hasChanges()) {
            return;
        }
        String uniquePropertyName = WorksheetUtils.getUniquePropertyName(worksheet);
        List<String> uniquePropertyValues = WorksheetUtils.getUniquePropertyValues(worksheet);
        //final Map<String, User> presidentsX;// = getUserService().getBy(uniquePropertyName, uniquePropertyValues);
        
        worksheet.processRows(new WorksheetCallbackHandler() {
            public void process(WorksheetRow worksheetRow) {
                Collection<WorksheetColumn> columns = worksheetRow.getColumns();
                for (WorksheetColumn worksheetColumn : columns) {
                    String changedValue = worksheetColumn.getChangedValue();

                    validateColumn(worksheetColumn, changedValue);
                    if (worksheetColumn.hasError()) {
                        continue;
                    }

                    String uniqueValue = worksheetRow.getUniqueProperty().getValue();
                    BaseUser president = (BaseUser)getUserService().get(uniqueValue);
                    String property = worksheetColumn.getProperty();

                    try {
                        if (worksheetColumn.getProperty().equals("selected")) {
                            if (changedValue.equals(CheckboxWorksheetEditor.CHECKED)) {
                                PropertyUtils.setProperty(president, property, "y");
                            } else {
                                PropertyUtils.setProperty(president, property, "n");
                            }

                        } else {
                            PropertyUtils.setProperty(president, property, changedValue);
                        }
                    } catch (Exception ex) {
                        throw new RuntimeException("Not able to set the property [" + property + "] when saving worksheet.");
                    }
                        
                    getUserService().save(president);
                }
            }
        });
    }

    /**
     * An example of how to validate the worksheet column cells.
     */
    private void validateColumn(WorksheetColumn worksheetColumn, String changedValue) {
        if (changedValue.equals("foo")) {
            worksheetColumn.setErrorKey("foo.error");
        } else {
            worksheetColumn.removeError();
        }
    }

    /**
     * @return Get the html for the table.
     */
    private String getHtml(TableFacade tableFacade) {
        // add a custom filter matcher to be the same pattern as the cell editor used
        tableFacade.addFilterMatcher(new MatcherKey(Date.class, "birthday"), new DateFilterMatcher("yyyy-MM-dd"));

        // set the column properties
        tableFacade.setColumnProperties("selected", "firstName", "lastName", "username", "created", "password");

        HtmlTable table = (HtmlTable) tableFacade.getTable();
        table.setCaption("Presidents");
        table.getTableRenderer().setWidth("600px");

        HtmlRow row = table.getRow();
        row.setUniqueProperty("id"); // the unique worksheet properties to identify the row

        HtmlColumn chkbox = row.getColumn("selected");
        chkbox.getCellRenderer().setWorksheetEditor(new CheckboxWorksheetEditor());
        chkbox.setTitle("&nbsp;");
        chkbox.setFilterable(false);
        chkbox.setSortable(false);

        HtmlColumn firstName = row.getColumn("firstName");
        firstName.setTitle("First Name");

        HtmlColumn lastName = row.getColumn("lastName");
        lastName.setTitle("Last Name");

        HtmlColumn born = row.getColumn("created");
        born.setEditable(false);
        born.getCellRenderer().setCellEditor(new DateCellEditor("yyyy-MM-dd"));

        return tableFacade.render(); // return the Html
    }

    
}

